import React, { useEffect, useState } from 'react'
import { View, Text, Image, Button, Swiper, SwiperItem, ScrollView, WebView, OfficialAccount } from "@tarojs/components";
import Taro, { useDidHide, useDidShow, useLoad, usePullDownRefresh } from "@tarojs/taro";

import { c } from "../../common/index.js";
import { Col, Empty, NavBar, Picker, Row, Tabs } from '@nutui/nutui-react-taro'
import { getReservationUserOff } from "../../api/yuyue.js";
import { pageMiniVideo, pageMiniVideoPublic, selectVideoList } from "../../api/video.js";

import { iconEnter1, empty01, iconRightWhite, iconTipBlue, iconEnter2, iconEnter3, iconEditCircle, iconStudy, iconYinhuan, iconShenhe, iconYinhuanRecord, xuexiku, iconAdd, iconMore, iconRightBlack, iconRightGray, iconRightGray2 } from "../../assets/files.js";
import { setStore, getStore } from "../../utils/localStore.js";

import { navigateTo } from "../../common/_.js";
import { baseUrl } from '../../utils/request.js'
import { selectMiniInfoBannerList } from "../../api/zixun.js";
import contextVideo from "./components/videoList/videoContext.js"
import { initGlobalData } from "../../utils/globalData.js";
import { trainingInfoList } from "../../api/apply.js";
import { loginInfo } from "../../api/system.js";
import dayjs from "dayjs";
import LoginModal from "../../components/login/index.jsx";
import YyItem from "./components/yyItem/index.js";
import ColumnTitle from "../../components/columnTitle/index.jsx";
import VideoList from "./components/videoList/index.js";
import "./index.scss";

export default function Home() {
  const [loginVisible, setLoginVisible] = useState(false);
  const [statusBarHeight, setStatusBarHeight] = useState(0);
  const [asyncList, setAsyncList] = useState([])
  const [current, setCurrent] = useState(0)
  const [autoplay, setAutoplay] = useState(true)
  const [curBanner, setCurBanner] = useState({})
  const [videoList, setVideoList] = useState([])
  const [auditNum, setAuditNum] = useState("")
  const [act, setAct] = useState("")
  const [videoTypeVisible, setVideoTypeVisible] = useState(false)


  useDidShow(() => {
    getBanner()
    roleList?.includes("AUDITOR") && getTrainingInfoList()
    setAutoplay(true)
  })

  useDidHide(() => {
    setAutoplay(false)
  })

  useEffect(() => {
    console.log("============");
    console.log(roleList?.includes("AUDITOR"));
    roleList?.includes("AUDITOR") && getTrainingInfoList()
    getBanner()


  }, [])

  useEffect(() => {
    initGlobalData().then();
  }, []);

  useLoad(() => {
    setStatusBarHeight(Taro.getSystemInfoSync().statusBarHeight);
    getRole()
    Taro.showShareMenu({
      withShareTicket: true,
      menus: ["shareAppMessage", "shareTimeline"],
    });
  });


  async function getBanner() {
    const { data, success } = await selectMiniInfoBannerList({})
    if (success) {
      setAsyncList(data)
      if (data.length > 0) {
        setCurBanner(current ? data[current] : data[0])
      }
    }

    Taro.hideLoading()
  }

  const [videoTypeId, setVideoTypeId] = useState('')
  useEffect(() => {
    getVideoList()
  }, [videoTypeId])
  async function getVideoList() {
    let res = {};
    if (!getStore("token")) {
      res = await pageMiniVideoPublic({ pageSize: 10, pageNo: 1, videoTypeId })
    } else {
      res = await pageMiniVideo({ pageSize: 10, pageNo: 1, videoTypeId })
    }

    if (res.success) {
      res.data.list.forEach((v, i) => {
        v.isPoster = 1
        v.imageFileUrl = baseUrl + v.imageFileUrl
        v.src = baseUrl + v.videoFileUrl
        // v.type = 'video/mp4'
        v.index = i
      })
      setVideoList(res.data.list)
    } else {
      Taro.showToast({ title: res.msg, icon: 'none' })
    }

    Taro.hideLoading();
  }

  function bannerClick(id) {
    if (!getStore("token")) {
      setLoginVisible(true);
      return;
    }
    navigateTo("/pages/zixun-detail/index", { id })
  }

  function indicator() {
    return (
      <div className="indicatorWrap">
        {/* <div className="curMore">
          {current + 1}/{asyncList.length}
        </div> */}
        <div style={{ display: "flex", flex: 1, marginTop: '6px', }}>
          {
            asyncList.map((v, i) => {
              return (
                <div style={{ width: '16px', height: '6px', borderRadius: '4px', marginRight: '6px', backgroundColor: current === i ? '#fff' : '#B4BBBD' }}></div>
              )
            })
          }
        </div>
        <div className="rightMore">
          <span
            className="moreXixun"
            onClick={() => {
              if (!getStore("token")) {
                setLoginVisible(true);
                return;
              }
              navigateTo("/pages/zixun-list/index")
            }}
          >更多资讯
          </span>
          <Image className="iconRightWhite" src={iconRightWhite} />
        </div>
      </div>
    )
  }

  function swiperChange(e) {
    setCurrent(e.detail.current)
    setCurBanner(asyncList[e.detail.current])
  }

  function tologin() {
    if (!getStore("token")) {
      setLoginVisible(true);
    }
  }

  usePullDownRefresh(() => {
    setTimeout(() => {
      onRefresh()
    }, 300)
  })

  async function onRefresh() {
    Taro.showLoading({
      title: "刷新中...",
    });
    getBanner()
    getVideoList()
    getTrainingInfoList()
    getRole()
    setTimeout(() => {
      Taro.hideLoading()
    }, 3000)
    Taro.stopPullDownRefresh(); // 关闭下拉效果
  }

  const [roleList, setRoleList] = useState([])
  const getRole = async () => {
    const { success, data } = await loginInfo()
    if (success) {
      data?.userInfoDto?.roles.includes("AUDITOR") && getTrainingInfoList()
      setRoleList(data?.userInfoDto?.roles)
    }

  }

  function changeIsPoster(item, index) {
    let arr = JSON.stringify(videoList)
    arr = JSON.parse(arr)
    arr.forEach(element => {
      if (element.id == item.id) {
        element.isPoster = 2
      } else {
        element.isPoster = 1
      }
    });
    setVideoList(arr)
    contextVideo.playOnce(index)
  }

  const getTrainingInfoList = async () => {
    const { data, success } = await trainingInfoList({
      userId: getStore("userInfo").id,
      auditState: 1,
      startDate: dayjs().subtract(151, 'day').format('YYYY-MM-DD'),
      endDate: dayjs().add(31, 'day').startOf('day').format('YYYY-MM-DD'),
    })
    if (success) {
      setAuditNum(data?.total)
    }
  }

  const [tabValue, setTabValue] = useState('0')
  const [tabs, setTabs] = useState([])

  useEffect(() => {
    getVideoType()
  }, [])
  function getVideoType() {
    selectVideoList({}).then(res => {
      if (res.success) {
        res.data?.forEach(v => {
          v.value = v.id
          v.text = v.typeName
        })
        setTabs(res.data)
        setVideoTypeId(res.data[0].id)
      }
    })
  }

  const confirmPicker = (list, value) => {
    console.log(value);
    setVideoTypeId(value.toString())
  }

  const toVideoList = () => {
    navigateTo("/packageB/pages/video-list/index")
  }

  return (
    <View className="index">
      <View className="homebg"></View>
      {
        !getStore("token") &&
        <View className="transportbg" onClick={() => tologin()}></View>
      }

      <View className="mianWrap">
        {/* <View
          className="homeNameWrap"
          style={{ marginTop: statusBarHeight + 10 + "px" }}
        >
          <Text className="homeName">玉溪市公共消防安全服务</Text>
        </View> */}
        {/* <NavBar
        style={{ backgroundColor: "#4D91FF", position: 'fixed', left: 0, top: statusBarHeight }}
      >
        <span>玉溪市公共消防安全服务</span>
      </NavBar> */}


        <>
          {
            asyncList.length > 0 &&
            <View className="swiperWrap" >
              <Swiper
                style={{ height: '190px' }}
                className='test-h'
                circular
                onChange={swiperChange}
                autoplay={autoplay}
              >
                {asyncList.map((item, index) => (
                  <SwiperItem key={item}>
                    <img onClick={() => bannerClick(item?.id)} width="100%" height="190px" src={baseUrl + item.infoFileUrl} alt="" />
                  </SwiperItem>
                ))}

              </Swiper>
              {
                indicator()
              }
            </View>
          }
        </>

      </View>

      <>
        {
          asyncList.length > 0 &&
          <View className="banerTit" onClick={() => bannerClick(curBanner?.id)}>
            <Text className="bannerTitle">{curBanner?.infoName}</Text>
          </View>
        }
      </>


      {/* <View>
      <OfficialAccount>
        <Text>test</Text>
      </OfficialAccount>
      </View> */}

      <View className="yyWrap">

        <Row>
          <Col span={12} >
            <YyItem
              title={"我要学习"}
              img={iconStudy}
              click={() => c.navigateTo("/packageB/pages/video-list/index")}
            />
          </Col>
          <Col span={12}>
            <YyItem
              title={"我要测试"}
              img={iconEnter1}
              click={() => c.navigateTo("/packageA/pages/test-type/index")}
            />
          </Col>
          <Col span={12}>
            <YyItem
              title={"我要培训"}
              img={iconEnter3}
              click={() => c.navigateTo("/pages/apply/index")}
            />
          </Col>

          <Col span={12}>
            <YyItem
              title={"隐患随手拍"}
              img={iconYinhuan}
              click={() => c.navigateTo("/packageB/pages/report-add/index")}
            />
          </Col>
          {
            roleList?.includes("AUDITOR") &&
            <Col span={12}>
              <YyItem
                title={"审核培训"}
                img={iconShenhe}
                auditNum={auditNum}
                click={() => c.navigateTo("/pages/audit-list/index")}
              />

            </Col>
          }
          {
            roleList?.includes("HIDDEN_DANGER") &&
            <Col span={12}>
              <YyItem
                title={"隐患记录"}
                img={iconYinhuanRecord}
                click={() => c.navigateTo("/pages/danger-list/index")}
              />
            </Col>
          }
        </Row>
      </View>

      <View className='titleSty'>
        <Image src={xuexiku} className="xxk" />
        <View className="moreWap" onClick={toVideoList}>
          <Text className="moreText">查看更多</Text>
          <Image className="iconRight" src={iconRightGray2} />
        </View>
      </View>
      {/* <Tabs
        style={{ marginTop: '12px' }}
        activeColor='blue'
        value={tabValue}
        onChange={(value) => {
          setTabValue(value)
          setVideoTypeId(tabs[value].id)
        }}
      >
        {
          tabs.map((v, i) => {
            return <Tabs.TabPane key={i} title={v.title}></Tabs.TabPane>
          })
        }
      </Tabs> */}

      <View className='videoTypeWrap'>
        {
          tabs.slice(0, 3).map((v, i) => {
            return (
              <View onClick={() => {
                setVideoTypeId(v.value)
              }}
                key={i}
                className='typeItemWrap'
              >
                <View className={videoTypeId == v.value ? 'itemTypeAct' : "itemType"}>
                  <Text>{v.text}</Text>
                </View>
              </View>
            )
          })
        }
        {
          tabs.length > 3 &&
          <View onClick={() => {
            setVideoTypeVisible(true)
          }}>
            <Image src={iconMore} className='moreIcon' />
          </View>
        }

      </View>

      <View className="videoWrap">
        {/* <ColumnTitle title1="学习" title2="精" title3="选" click={() => {
          navigateTo("/pages/video-list/index")
        }} /> */}
        {
          videoList.length > 0 ? <VideoList videoList={videoList} changeIsPoster={changeIsPoster} />
            :
            <View className="emptyWrap">
              <Empty
                description="无数据"
                image={
                  <img
                    src={empty01}
                    alt=""
                  />
                }
              />
            </View>
        }

      </View>

      {
        videoList.length > 0 &&
        <View className='moreVideobtn' onClick={toVideoList}>
          <View>
            <Text>点击查看更多视频</Text>
          </View>
        </View>
      }


      <LoginModal
        visible={loginVisible}
        close={() => {
          setLoginVisible(false);
        }}
      />

      <Picker
        title="请选择视频类型"
        visible={videoTypeVisible}
        options={tabs}
        onConfirm={(list, values) => confirmPicker(list, values)}
        onClose={() => setVideoTypeVisible(false)}
      />


    </View>
  );
}
